import { check } from '@tauri-apps/plugin-updater';
import { onMounted, Ref, ref } from 'vue';

export function useUpdateChecker(): {
  updateChecked: Ref<boolean>;
  updateAvailable: Ref<boolean>;
} {
  const updateChecked = ref(false);
  const updateAvailable = ref(false);

  onMounted(checkUpdate);

  async function checkUpdate(): Promise<void> {
    // If has internet connectivity then we need to check available update.
    if (navigator.onLine) {
      try {
        const update = await check();
        updateAvailable.value = update?.rid != null;
      } catch {
        // Even with internet connectivity network access still might be not available.
        // We need to ignore such issue and continue.
      }
    }

    updateChecked.value = true;
  }

  return {
    updateChecked,
    updateAvailable,
  };
}
